<?php
namespace app\modules\developer\models;
use common\component\tool\Tool;
use app\models\Basic;

use Yii;

class AppCategory extends Basic
{
    
    public static function tableName()
    {
        return '{{%app_category}}';
    }

    public function rules()
    {
        return [
            ['cat_name', 'required', 'message' => 'cat_name不能为空', 'on' => 'add'],
            ['cat_name', 'string', 'message' => 'cat_name必须是字符串',
                         'min' => 2, 'tooShort' => 'cat_name最短2位',
                         'max' => 16, 'tooLong' => 'cat_name最长16位'],
            ['icon', 'default', 'value' => ''],
            ['icon', 'string', 'message' => 'icon必须是字符串', 
                     'max' => 32, 'tooLong' => 'icon最长32位'],
            ['sort', 'integer', 'message' => 'sort必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'sort最小存储0', 
                     'max'=>255, 'tooBig' => 'sort最大存储255'],
            ['display', 'default', 'value' => 1],
            ['display', 'integer', 'message' => 'display必须为数字，或数字字符串'],
            ['display', 'in', 'range' => array(1, 2), 'message' => 'display值必须在1,2中选择'],
        ];
    }


    /*添加分类*/
    public function addCategory($data)
    {
        // P($data);
        if(isset($data['AppCategory']['display'])){
            $data['AppCategory']['display'] = Tool::changeBool($data['AppCategory']['display']);
        }
        $this->scenario = 'add';
        if($this->load($data) and $this->validate()){
            if($this->save(false)){
                $app_cat_id = $this->getPrimaryKey();
                $this->updateAll(['sort' => $app_cat_id], 'app_cat_id = :id', [':id' => $app_cat_id]);
                return true;
            }
        }
        return false;
    }

    /*
    修改分类
    $data   修改的数据
    $id     分类ID
    $flag   值为setDisplay时 作用是更改是否显示，为空是修改菜单
    */
    public function modifyCategory($data, $id, $flag = '')
    {
        if($flag != 'setDisplay'){
            $this->scenario = 'add';
        }
        if(isset($data['AppCategory']['display'])){
            $data['AppCategory']['display'] = Tool::changeBool($data['AppCategory']['display']);
        }
        $appCategory = AppCategory::find()->where('app_cat_id = :id', [':id' => $id])->one();
        if(!is_null($appCategory)){
            if($this->load($data) and $this->validate()){
                if(!empty($this->cat_name) and empty($flag)){
                    $appCategory->cat_name = $this->cat_name;
                }
                if(!empty($this->icon) and empty($flag)){
                    $appCategory->icon = $this->icon;
                }
                if(!empty($this->display)){
                    $appCategory->display = $this->display;
                }
                if($appCategory->save(false)){
                    return true;
                }
            }
        };
        return false;
    }
    
}